const compressing = require('compressing');
const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');

async function compressIgnoringGitAndBuild(sourceDir, destPath) {
    try {
        console.log(`正在压缩 ${sourceDir}，自动忽略 .git 和 build 文件夹...`);

        // 创建可写流
        const zipStream = new compressing.zip.Stream();
        const destStream = fs.createWriteStream(destPath);

        // 递归添加文件到压缩流，自动忽略指定文件夹
        await addFilesToZip(zipStream, sourceDir, '');

        // 管道传输到目标文件
        zipStream.pipe(destStream);

        return new Promise((resolve, reject) => {
            destStream.on('finish', () => {
                console.log(`压缩完成: ${destPath}`);
                resolve(destPath);
            });

            destStream.on('error', reject);
        });
    } catch (error) {
        console.error('压缩出错:', error);
        throw error;
    }
}

// 递归添加文件并自动忽略 .git 和 build 文件夹
async function addFilesToZip(zipStream, basePath, relativePath) {
    const fullPath = path.join(basePath, relativePath);
    const stats = fs.statSync(fullPath);

    if (stats.isDirectory()) {
        // 检查是否是要忽略的文件夹
        const dirName = path.basename(fullPath);
        if (dirName === '.git' || dirName === 'build') {
            console.log(`[自动忽略] ${fullPath}`);
            return;
        }

        const files = fs.readdirSync(fullPath);

        for (const file of files) {
            const fileRelativePath = path.join(relativePath, file);
            await addFilesToZip(zipStream, basePath, fileRelativePath);
        }
    } else {
        zipStream.addEntry(fullPath, {
            relativePath: relativePath,
            ignoreBase: true
        });
    }
}

// 跨平台打开文件夹
function openDestFolder(folderPath) {
    let command;
    switch (process.platform) {
        case 'darwin':  // macOS
            command = `open "${folderPath}"`;
            break;
        case 'win32':   // Windows
            command = `explorer "${folderPath.replace(/\//g, '\\')}"`;
            break;
        default:        // Linux
            command = `xdg-open "${folderPath}"`;
            break;
    }

    exec(command, (error) => {
        if (error) {
            console.error(`无法打开文件夹: ${error}`);
        } else {
            console.log(`已打开目标文件夹: ${folderPath}`);
        }
    });
}

// 使用示例
const sourceDir = 'D:/gitlab/smarthome_plugin/projects/com.mova.toothbrush';  // 要压缩的项目文件夹
const destPath = 'C:/Users/22698/Desktop/打包后的产物/publish.mpkg';  // 压缩包输出路径

compressIgnoringGitAndBuild(sourceDir, destPath)
    .then(() => {
        console.log('压缩成功! 已自动忽略 .git 和 build 文件夹')
        // 打开目标文件夹
        openDestFolder("C:/Users/22698/Desktop/打包后的产物");
    })
    .catch(err => console.error('压缩失败:', err));